package org.karelun.whiteboard.policy;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.command.CreateChildCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.karelun.whiteboard.Sheet;
import org.karelun.whiteboard.Triangle;
import org.karelun.whiteboard.WhiteboardFactory;
import org.karelun.whiteboard.WhiteboardPackage;
import org.karelun.whiteboard.editparts.TriangleEditPart;
import org.karelun.whiteboard.gef.EditPart;
import org.karelun.whiteboard.gef.editpolicies.XYLayoutEditPolicy;
import org.karelun.whiteboard.gef.requests.ChangeBoundsRequest;
import org.karelun.whiteboard.gef.requests.CreateRequest;

/**
 * @Author: KarelunHuang
 * @Date: Jan 23, 2013
 **/
public class SheetLayoutEditPolicy extends XYLayoutEditPolicy {

	@Override
	protected Command getCreateCommand(CreateRequest request) {
		Object newObject = request.getNewObject();
		if(newObject==null){
			newObject=WhiteboardFactory.eINSTANCE.createTriangle();
		}
		Triangle triangle=(Triangle)newObject;
		Rectangle constraint=(Rectangle)getConstraintFor(request);
		triangle.setX(constraint.x);
		triangle.setY(constraint.y);
		triangle.setHeight(50);
		triangle.setWidth(50);
		
		List<Object> collection=new ArrayList<Object>();
		Sheet sheet=(Sheet)getHost().getModel();
		collection.add(sheet);
		CommandParameter descriptor = new CommandParameter(null, WhiteboardPackage.Literals.SHEET__GRAPHS, triangle);
		return CreateChildCommand.create(getEditingDomain(), sheet, descriptor,collection);
	}
	
	@Override
	protected Command createChangeConstraintCommand(ChangeBoundsRequest request, EditPart child, Object constraint) {
		if (!(child instanceof TriangleEditPart))
            return null;
        if (!(constraint instanceof Rectangle))
            return null;
        Triangle shape=(Triangle)child.getModel();
        Rectangle bound=(Rectangle)constraint;
        
        CompoundCommand ret = new CompoundCommand();
        Command xcommand = SetCommand.create(getEditingDomain(), shape, WhiteboardPackage.Literals.LOCATION__X, new Integer(bound.x));
        Command ycommand = SetCommand.create(getEditingDomain(), shape, WhiteboardPackage.Literals.LOCATION__Y, new Integer(bound.y));
        Command wcommand = SetCommand.create(getEditingDomain(), shape, WhiteboardPackage.Literals.DIMENSION__WIDTH, new Integer(bound.width));
        Command hcommand = SetCommand.create(getEditingDomain(), shape, WhiteboardPackage.Literals.DIMENSION__HEIGHT, new Integer(bound.height));
        ret.append(xcommand);
        ret.append(ycommand);
        ret.append(wcommand);
        ret.append(hcommand);
        return ret;
	}
	
}
